
/*bertrand first order conditions for aids demand.  s a nbrnds x 1 matrix of pre-merger revenue shares, p a nbrnds x 1 matrix of pre-merger prices, c is pre-merger cost, g are the coefficients on lnp from the aids model, b is the coefficient on ln(X/P), w are average revenue shares, and ex is expenditures.*/

mata
function aids(x,s,p,c,g,b,w,ex,e)
{	
	/*create intercepts such that premerger prices predict pre-merger shares perfectly (won't always use sample means, so this is necessary*/
	cept=J(rows(c),1,0)
	aidfoc=J(7,cols(x),0)
	sh=J(7,cols(x),0)
	for(i=1;i<=rows(c);i++){
		cept[i,1]=s[i,1]+b[i,1]*(w'*ln(p))-b[i,1]*ln(ex)-ln(p)'*g[i,.]'
	}
	for(j=1;j<=cols(x);j++){
		for(i=1;i<=rows(c);i++){
			sh[i,j]=cept[i,1]+b[i,1]*ln(ex)-b[i,1]*(w'*ln(x[.,j]))+ln(x[.,j])'*g[i,.]'
		}
		aidfoc[1,j]=((x[1,j]-c[1,1])/x[1,j])*((1/sh[1,j])*(g[1,1]-b[1,1]*w[1,1])-1+(1+e)*w[1,1]*(1+b[1,1]/sh[1,j]))*sh[1,j]+sh[1,j]

		aidfoc[2,j]=((x[2,j]-c[2,1])/x[2,j])*((1/sh[2,j])*(g[2,2]-b[2,1]*w[2,1])-1+(1+e)*w[2,1]*(1+b[2,1]/sh[2,j]))*sh[2,j]+sh[2,j]

		aidfoc[3,j]=((x[3,j]-c[3,1])/x[3,j])*((1/sh[3,j])*(g[3,3]-b[3,1]*w[3,1])-1+(1+e)*w[3,1]*(1+b[3,1]/sh[3,j]))*sh[3,j]+sh[3,j]

		aidfoc[4,j]=((x[4,j]-c[4,1])/x[4,j])*((1/sh[4,j])*(g[4,4]-b[4,1]*w[4,1])-1+(1+e)*w[4,1]*(1+b[4,1]/sh[4,j]))*sh[4,j]+((x[6,j]-c[6,1])/x[6,j])*((1/sh[6,j])*(g[6,4]-b[6,1]*w[4,1])+(1+e)*w[4,1]*(1+b[6,1]/sh[6,j]))*sh[6,j]+sh[4,j]

		aidfoc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